package com.itheima.infoManager.arraylistDemo.manager.dao;

import com.itheima.infoManager.arraylistDemo.manager.domain.Student;

public class StudentDao extends BaseStudentDao{
    private static Student[] stus = new Student[5];

    static {
        Student stu1 = new Student("heima001","张三","23","1998-88-99");
        Student stu2 = new Student("heima002","李四","24","2000-88-99");

        stus[0]=stu1;
        stus[1]=stu2;
    }

    //添加
    @Override
    public boolean addStudent(Student stu) {
        for (int i = 0; i < stus.length; i++) {
            Student stu1 = stus[i];
            if (stu1==null){ //有数组索引处为空的地方
                stus[i]=stu; //就可以插入要添加的对象
                return true; //向上层返回true
            }
        }
            return false;//否则返回false
    }

    //返回数组——查看
    @Override
    public Student[] findAllStudent() {
        return stus;
    }

    //删除
    public boolean deleteStudent(String delId) {
        //调用getIndex方法，取得当前id在数组的索引位置
        int index = getIndex(delId);
        if (index==-1){
            return false;
        }else {
            stus[index]=null;
            return true;
        }
    }

    //根据id查找其学生对象所在数组索引处
    public int getIndex(String id) {
        for (int i = 0; i < stus.length; i++) {
            Student stu = StudentDao.stus[i];
            if (stu!=null&&stu.getId().equals(id)){
                return i;
            }
        }
        return -1;
    }

    //修改
    public boolean updateStudent(String upId, Student student) {
        //根据id查找其学生对象所在数组索引处
        int index = getIndex(upId);
        if (index==-1){
            return false;
        }else{
            stus[index]=student;
            return true;
        }

    }
}
